FROM node:20-alpine AS base

RUN npm install -g pnpm

# 设置工作目录
WORKDIR /app

# 复制package.json和pnpm-lock.yaml
COPY package.json .npmrc pnpm-lock.yaml ./

# 构建阶段
FROM base AS builder

# 安装所有依赖（包括开发依赖）
RUN pnpm install --frozen-lockfile

# 复制源代码
COPY . .

# 构建应用
RUN pnpm run build

# 生产阶段
FROM base AS production

# 设置环境变量
ENV NODE_ENV=production
ENV PORT=3000
ENV AIBOTID="aibNedDGmwYpDNZY17Y0A11rTOjGGwhDPQC"

# 创建非root用户
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nestjs -u 1001

# 只安装生产依赖
RUN pnpm install --prod --frozen-lockfile && \
    pnpm store prune

# 从构建阶段复制构建产物
COPY --from=builder --chown=nestjs:nodejs /app/dist ./dist

# 切换到非root用户
USER nestjs

# 暴露端口
EXPOSE 3000

# 启动应用
CMD ["node", "dist/main.js"]
